package com.crm.service.crm.businessOpportunities.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.model.common.constants.CustomInfoConstants;
import com.crm.model.common.dtos.ResponseResult;
import com.crm.model.common.enums.AppHttpCodeEnum;
import com.crm.model.crm.businessOpportunities.dto.ReasonDto;
import com.crm.model.crm.businessOpportunities.dto.RecordsAllDto;
import com.crm.model.crm.businessOpportunities.dto.RecordsDto;
import com.crm.model.crm.businessOpportunities.pojo.CustomInfo;
import com.crm.model.crm.businessOpportunities.pojo.Intention;
import com.crm.model.crm.businessOpportunities.pojo.Records;
import com.crm.model.crm.businessOpportunities.vo.RecordsVo;
import com.crm.model.system.pojo.User;
import com.crm.service.crm.businessOpportunities.mapper.CustomInfoMapper;
import com.crm.service.crm.businessOpportunities.mapper.IntentionMapper;
import com.crm.service.crm.businessOpportunities.mapper.RecordsMapper;
import com.crm.service.crm.businessOpportunities.service.RecordsService;
import com.crm.utils.ThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class RecordsServiceImpl extends ServiceImpl<RecordsMapper, Records> implements RecordsService {

    @Autowired
    private RecordsMapper recordsMapper;

    @Autowired
    private CustomInfoMapper customInfoMapper;

    @Autowired
    private IntentionMapper intentionMapper;


    //保存客户跟进信息
    @Override
    public ResponseResult saveAll(RecordsAllDto recordsAllDto) {
        //健壮性判断
        if (recordsAllDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //客户姓名为空判断
        if (recordsAllDto.getCustomName() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NAME_NULL);
        }
        //客户电话为空判断
        if (recordsAllDto.getPhone() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PHONE_NULL);
        }
        //意向学科为空判断
        if (recordsAllDto.getIntentionalCourses() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.INTENTIONALCOURSES_NULL);
        }
        //意向课程判断
        if (recordsAllDto.getIntentionalDiscipline() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.INTENTIONALDISCIPLINE_NULL);
        }
        //跟进状态判断
        if (recordsAllDto.getFollowUpStatus() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.FOLLOW_Up_STATUS_NULL);
        }
        //下次跟进时间判断
        if (recordsAllDto.getNextFollowTime() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEXT_FOLLOW_UP_TIME);
        }
        //沟通重点判断
        if (recordsAllDto.getCommunicationFocus() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMUNICATION_FOCUS);
        }
        //沟通纪要判断
        if (recordsAllDto.getCommunicationMinutes() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMUNICATION_MINUTES);
        }
        //处理客户表
        dealWithCustomInfo(recordsAllDto);

        //处理客户意向表
        dealWithIntention(recordsAllDto);

        //处理沟通交流表
        dealWithRecord(recordsAllDto);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    //回显客户跟进信息
    @Override
    public ResponseResult getById(Integer id) {

        //获取跟进信息表

         //查询客户详细信息
        CustomInfo customInfo = customInfoMapper.selectById(id);
         //查询客户详细意向
        Intention byCustomId = intentionMapper.getByCustomId(id);
         //查询历史沟通表
        List<Records> byCustomId1 = recordsMapper.getByCustomId(id);

        //处理历史沟通记录表
        List<RecordsDto> recordsDtoList = getRecordsDtos(byCustomId1);

        //返回
        return ResponseResult.okResult(getRecordsVo(customInfo, byCustomId, recordsDtoList));
    }


    //保存回退信息表
    @Override
    public ResponseResult saveReason(ReasonDto reasonDto) {
        //健壮性判断
        if (reasonDto.getReason() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //查询客户信息
        CustomInfo customInfo = customInfoMapper.selectById(reasonDto.getCurstomId());
        //处理客户信息表
        dealWithCustonInfo(reasonDto, customInfo);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    //处理沟通记录表
    private void dealWithRecord(RecordsAllDto recordsAllDto) {
        //新建沟通交流表
        Records records = new Records();
        //复制信息
        BeanUtils.copyProperties(recordsAllDto,records);

        //添加本次沟通时间
        records.setTimeOfThisCommunication(LocalDate.now());
        User user = ThreadLocalUtil.getUser();

        //添加沟通人
//        records.setCommunicationPerson(user.getName());
        records.setCommunicationPerson("2");

        //添加沟通人id
//        records.setCommunicationId(user.getId());
        records.setCommunicationId(2);

        //添加沟通重点
        List<String> communicationFocus = recordsAllDto.getCommunicationFocus();

        //将沟通重点转换为字符串类型加入
        String focus = StringUtils.join(communicationFocus);
        records.setCommunicationFocus(focus);

        //插入沟通记录表
        recordsMapper.insert(records);
    }

    //处理客户意向表
    private void dealWithIntention(RecordsAllDto recordsAllDto) {
        //新建客户意向表
        Intention intention = new Intention();
        //复制意向信息
        BeanUtils.copyProperties(recordsAllDto,intention);
        //添加创建用户，从threadlocl中拿去
        User user = ThreadLocalUtil.getUser();
//        intention.setCreatePeople(user.getName());
        intention.setCreatePeople("2");
        //添加当前时间
        intention.setCreateTime(LocalDate.now());
        //插入数据
        intentionMapper.insert(intention);
    }

    //处理客户表
    private void dealWithCustomInfo(RecordsAllDto recordsAllDto) {
        //查询客户资料表
        CustomInfo customInfo = customInfoMapper.selectById(recordsAllDto.getCustomId());
        //复制已有信息
        BeanUtils.copyProperties(recordsAllDto,customInfo);
        //补充信息
        //修改客户名字（因为两张表的字段不一样）
        customInfo.setName(recordsAllDto.getCustomName());
        //添加归属人，从threadlocl中获取
        //获取登录用户的信息
        User user = ThreadLocalUtil.getUser();
//        customInfo.setUpdatePeople(user.getName());
        customInfo.setUpdatePeople("2");
        //更新时间
        customInfo.setUpdateTime(LocalDate.now());
        //更新数据
        customInfoMapper.updateById(customInfo);
    }

    //打包
    private RecordsVo getRecordsVo(CustomInfo customInfo, Intention byCustomId, List<RecordsDto> recordsDtoList) {
        RecordsVo recordsVo = new RecordsVo();
        //判断该客户是否已经有意向表
        if (byCustomId !=null){
            BeanUtils.copyProperties(byCustomId,recordsVo);
        }
        BeanUtils.copyProperties(customInfo,recordsVo);
        recordsVo.setRecordsList(recordsDtoList);
        return recordsVo;
    }

    //处理历史沟通记录表
    private List<RecordsDto> getRecordsDtos(List<Records> byCustomId1) {
        //获取返回的沟通记录表
        List<RecordsDto> recordsDtoList = new ArrayList<>();
        for (Records records : byCustomId1) {
            String communicationFocus = records.getCommunicationFocus();
            String[] split = communicationFocus.split(",");
            split[0] = split[0].substring(1);
            split[split.length-1] = split[split.length-1].substring(0, split[split.length-1].length() - 1);
            RecordsDto recordsDto = new RecordsDto();
            BeanUtils.copyProperties(records,recordsDto);
            recordsDto.setCommunicationFocus(Arrays.asList(split));
            recordsDtoList.add(recordsDto);
        }
        return recordsDtoList;
    }

    //处理客户信息表
    private void dealWithCustonInfo(ReasonDto reasonDto, CustomInfo customInfo) {
        //添加回退原因
        customInfo.setReasonForReturn(reasonDto.getReason());
        //清楚归属人
        customInfo.setRevert(CustomInfoConstants.NOT_REVERT);
        //更新客户表
        customInfoMapper.updateById(customInfo);
    }
}
